#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>

// led PA15

#define LED_MAJOR		200		/* 主设备号 */
#define LED_NAME		"led" 	/* 设备名字 */

#define LEDON   0
#define LEDOFF  1

#define PA_CFG1_ADDR    (0x01c20804)
#define PA_DATA_ADDR    (0x01c20810)

static void __iomem *PA_CFG1;
static void __iomem *PA_DATA;

void led_switch(u8 sta)
{
    u32 val = 0;
	if(sta == LEDON) {
		val = readl(PA_DATA);
		val &= ~(1 << 15);	
		writel(val, PA_DATA);
	}else if(sta == LEDOFF) {
		val = readl(PA_DATA);
		val|= (1 << 15);	
		writel(val, PA_DATA);
	}	
}

static int led_open(struct inode *inode, struct file *filp)
{
	return 0;
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
	int retvalue;
	unsigned char databuf[1];
	unsigned char ledstat;

	retvalue = copy_from_user(databuf, buf, cnt);
	if(retvalue < 0) {
		printk("kernel write failed!\r\n");
		return -EFAULT;
	}

	ledstat = databuf[0];		/* 获取状态值 */

	if(ledstat == LEDON) {	
		led_switch(LEDON);		/* 打开LED灯 */
	} else if(ledstat == LEDOFF) {
		led_switch(LEDOFF);	/* 关闭LED灯 */
	}
	return 0;
}

static int led_release(struct inode *inode, struct file *filp)
{
	return 0;
}

static struct file_operations led_fops = {
	.owner = THIS_MODULE,
	.open = led_open,
	//.read = led_read,
	.write = led_write,
	.release = 	led_release,
};

static int __init led_init(void)
{
    int retvalue = 0;
	u32 val = 0;

    PA_CFG1=ioremap(PA_CFG1_ADDR,4);
    PA_DATA=ioremap(PA_DATA_ADDR,4);

    val=readl(PA_CFG1);
    val&=~(1<<28);
    val|=(1<<28);
    writel(val,PA_CFG1);

    retvalue = register_chrdev(LED_MAJOR, LED_NAME, &led_fops);
	if(retvalue < 0){
		printk("register chrdev failed!\r\n");
		return -EIO;
	}
    return 0;
}

static void __exit led_exit(void)
{
    iounmap(PA_CFG1);
    iounmap(PA_DATA);

    unregister_chrdev(LED_MAJOR, LED_NAME);
}

module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("HRX");

